package com.junci.mtest.utils;

import android.content.Context;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
 
public class VideoSurfaceView extends SurfaceView implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener {
 
    private MediaPlayer mediaPlayer;
    private playCallback callback ;

    public playCallback getCallback() {
        return callback;
    }

    public void setCallback(playCallback callback) {
        this.callback = callback;
    }

    public interface playCallback {
        void onPlay();
    }
    private SurfaceHolder holder;
 
    public VideoSurfaceView(Context context) {
        super(context);
        init();
    }
 
    public VideoSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
 
    public VideoSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
 
    private void init() {
        holder = getHolder();
        holder.addCallback(this);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(this);
    }
    public void setlooping(boolean loop){
        mediaPlayer.setLooping(loop);
    }
 
    public void setVideoPath(String videoPath) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(videoPath);
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mediaPlayer.setDisplay(holder);
    }
 
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }
 
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
    }
 
    @Override
    public void onPrepared(MediaPlayer mp) {
        mediaPlayer.start();
        if (callback != null) {
            callback.onPlay();
        }
    }
}